package com.psq.core.common.di

import com.google.gson.GsonBuilder
import com.psq.core.common.BuildConfig
import com.psq.core.common.network.interceptor.BasicParamsInterceptor
import com.psq.core.common.network.interceptor.HeaderInterceptor
import com.psq.core.common.network.interceptor.LoggingInterceptor
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Singleton

@Module
@InstallIn(SingletonComponent::class)
/** 单例 */
object RetrofitModule {

    /** 请求超时时间 */
    private const val TIME_OUT_SECONDS = 10

    /** 服务地址 */
    private const val BASE_URL = BuildConfig.BASE_URL

    @Singleton
    @Provides
    fun provideHttpClient(): OkHttpClient {
        return OkHttpClient.Builder()
            // Log
            .addInterceptor(LoggingInterceptor())
            // Basic Params
            .addInterceptor(BasicParamsInterceptor())
            // Header
            .addInterceptor(HeaderInterceptor())
            // Timeout
            .connectTimeout(TIME_OUT_SECONDS.toLong(), TimeUnit.SECONDS)
            .build()
    }

    @Singleton
    @Provides
    fun provideRetrofit(httpClient: OkHttpClient): Retrofit {
        val builder = Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(httpClient)
            .addConverterFactory(
                GsonConverterFactory.create(
                    GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create()
                )
            )
        return builder.build()
    }

    fun <T> create(serviceClass: Class<T>): T =
        provideRetrofit(provideHttpClient()).create(serviceClass)

}